package cn.jfstu.freenote.mvc.controller.extend;

import cn.jfstu.freenote.entity.extend.User;
import cn.jfstu.freenote.exception.extend.AppException;
import cn.jfstu.freenote.exception.message.ExceptionCode;
import cn.jfstu.freenote.mvc.annotation.DisableLoginCheck;
import cn.jfstu.freenote.mvc.assist.Session;
import cn.jfstu.freenote.mvc.controller.base.BaseController;
import cn.jfstu.freenote.mvc.controller.response.AppResponse;
import cn.jfstu.freenote.mvc.controller.response.BaseResponse;
import cn.jfstu.freenote.service.extend.UserService;
import cn.jfstu.freenote.util.string.MD5Util;
import cn.jfstu.freenote.util.string.RandomUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 身份验证控制器
 *
 * @author 贾俊峰
 * @version 1.0
 * @date 2016/12/26 16:31
 */
@Controller
@RequestMapping("/auth")
public class AuthController extends BaseController {
    @Resource
    private UserService userService;

    /**
     * 注册
     *
     * @param email    用户邮箱（也是用户名）
     * @param password 用户密码
     */
    @RequestMapping("/register")
    @ResponseBody
    @DisableLoginCheck
    public BaseResponse register(String email, String password) {
        User user = userService.getByUsername(email);
        if (user != null) { // 用户名重复
            throw new AppException(ExceptionCode.EMAIL_ALREADY_EXIST);
        }

        user = new User();
        user.setUsername(email);
        user.setEmail(email);
        String salt = RandomUtil.getRandomString(6, RandomUtil.Type.ALL);
        user.setSalt(salt);
        password = MD5Util.md5(password + salt);
        user.setPassword(password);
        userService.add(user);
        return new AppResponse();
    }

    @RequestMapping("/emailCheck")
    @ResponseBody
    @DisableLoginCheck
    public boolean emailCheck(String email) {
        return userService.getByUsername(email) == null;
    }

    @RequestMapping("/login")
    @ResponseBody
    @DisableLoginCheck
    public BaseResponse login(String username, String password, HttpSession session) {
        // 验证用户名
        User user = userService.getByUsername(username);
        if (user == null) {
            throw new AppException(ExceptionCode.USERNAME_NOT_EXIST);
        }

        // 验证密码
        password = MD5Util.md5(password + user.getSalt());
        if (!password.equals(user.getPassword())) {
            throw new AppException(ExceptionCode.PASSWORD_MISTAKE);
        }

        // 登录成功,设置session
        session.setAttribute(Session.LOGIN_USER, user);

        return new AppResponse();
    }

    @RequestMapping("/logout")
    @ResponseBody
    public void logout() {}


}
